package cn.gaaidou.rpc.framework;

import cn.gaaidou.common.utils.IOUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Martin
 * @date 2021/7/3 13:04
 */
@Slf4j
public class RpcServer {

    private volatile boolean stop = false;

    private ServerSocket serverSocket;

    /**
     * 创建一个ServerSocket, 默认端口为8080
     *
     * @param port
     * @throws IOException
     */
    public RpcServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public RpcServer() throws IOException {
        this(8080);
    }

    public void start() {
        // 1、注册关闭回勾
        Runtime.getRuntime().addShutdownHook(new Thread(() -> stop = true));
        while (!stop) {
            try {
                // 2、监听客户端Socket
                Socket socket = serverSocket.accept();
                // 3、读取请求 -> 执行请求 -> 响应结果
                socket.getOutputStream().write(RpcInvoker.invoke(IOUtil.readSocket(socket.getInputStream())));
                // 4、关闭Socket
                socket.close();
            } catch (Exception e) {
                log.error("Socket监听出现异常, 异常原因: {}", e.getMessage(), e);
            }
        }
    }
}
